﻿using Npgsql;

namespace EOrm.NpgsqlProvider
{
    /// <summary>
    /// postgres数据库
    /// </summary>
    public class PgDb : Db
    {
        /// <summary>
        /// 私有构造函数
        /// </summary>
        private PgDb() { }

        /// <summary>
        /// 创建postgres数据库实例
        /// </summary>
        /// <param name="jsonConfigPathOrConString">json配置文件路径或连接字符串</param>
        /// <returns>postgres数据库</returns>
        internal static Db CreateInstance(string jsonConfigPathOrConString)
        {
            if (_dbInstance == null)
            {
                lock (_dbLock)
                {
                    if (_dbInstance == null)
                    {
                        ConStr conString = PgConStr.CreateInstance(jsonConfigPathOrConString);
                        NpgsqlConnection conInstance = new NpgsqlConnection(conString.ConnectionString);
                        _dbInstance = new PgDb();
                        _dbInstance.DbCon = conInstance;
                        _dbInstance.Name = conInstance.Database;
                    }
                }
            }
            return _dbInstance;
        }

        /// <summary>
        /// 获取数据库
        /// </summary>
        /// <returns>数据库</returns>
        /// <exception cref="ArgumentException">变量为空异常</exception>
        internal static PgDb GetDb()
        {
            if (_dbInstance== null)
            {
                throw new ArgumentException("数据库实例为空", "_dbInstance");
            }
            PgDb? res = _dbInstance as PgDb;
            if (res == null)
            {
                throw new ArgumentException("数据库实例转换失败", "res");
            }
            return res;
        }

        /// <summary>
        /// 获取postgres数据库链接
        /// </summary>
        /// <returns>postgres数据库链接</returns>
        /// <exception cref="ArgumentException">变量为空异常</exception>
        internal NpgsqlConnection GetCon()
        {
            if (this== null)
            {
                throw new ArgumentException("数据库实例为空", "_dbInstance");
            }
            NpgsqlConnection? res = this.DbCon as NpgsqlConnection;
            if (res == null)
            {
                throw new ArgumentException("向postgres数据库连接转换失败", "res");
            }
            return res;
        }
    }
}
